#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
@Author: 李吉凯
@Email: lijk34925@hundsun.com
@Time: 2022/5/10 9:42
@File: basic.py
"""
import time

from qturboframe.lib.common.web_config import web_config
from qturboframe.lib.utils.by import By
from qturboframe.lib.webdriver import SeleniumError
from selenium.webdriver.common.keys import Keys

from BladeFerm.hui12_common.function import display_wait
from BladeFerm.Lib.Common import *
from BladeFerm.hui_app import FE, debugger
from BladeFerm.hui_app.hui_lib.home_tab import HomeTab
from BladeFerm.utils.killDriver import KillChromedriver


def sys_login(username, password,url):
    '''
    用户登录
    :input_data:
     - 用户名: 用户名
     - 密码: 密码
    :ui_expect:
    '''
    if debugger:
        logger.debug(f'代理调试模式')
        return True
    # url = config.get('Browser', 'mainpage_url')
    # 判断页面是否打开
    # if not (web_config.last_url and web_config.last_url == url):
    FE.driver.get(url)
    web_config.last_url = url
    # 判断该用户名是否已登录
    # if not web_config.last_login_name:
    #     logger.info('用户不存在，尚未登录！')
    # elif web_config.last_login_name != username:
    #     FE.driver.refresh()
    #     __logout(FE.driver)
    # else:
    #     # 判断页面是否可操作
    #     pop = FE.msg_box(timeout=0.1).exist()
    #     logger.info('判断弹框时间')
    #     if pop:
    #         # 刷新页面
    #         FE.driver.refresh()
    #         logger.info('刷新时间')
    #     return
    # 登录首页
    __login(FE.driver, username, password)
    res_check = display_wait(idname={By.CSS_SELECTOR: 'div.h-layout-head-sys-item'}, flag=0,
                             timeout=10, driver=FE.driver)
    logger.info(f'check child system load finished : {res_check}')

def sys_logout():
    '''
    登出并判断是否关闭浏览器驱动
    :param:
    :return:
    '''
    # debugger = True
    if debugger:
        logger.debug(f'代理调试模式')
        return True
    username = web_config.last_login_name
    __logout(FE.driver)
    logger.info(f'用户: {username} 退出登录！')


def close_brower(flag=True):
    '''
    关闭驱动，打开的浏览器窗口，以及驱动窗口
    :return:
    '''
    status = False
    debugger = config.get('Browser', 'debugger')
    if flag and debugger != 'True':
        FE.driver.close()
        logger.info('关闭浏览器。')
        status = True
        web_config.last_url = ''
        web_config.last_login_name = ''
    else:
        logger.warning('未关闭浏览器！')
    __close_driver(flag)
    return status

def __login(driver, user_name, password):
    '''
    登录
    :param driver:
    :param user_name:
    :param password:
    :return:
    '''
    username_text = FE.input_type({By.XPATH: '//input[@placeholder="用户名"]'}, driver)
    username_text.set_value(user_name)
    web_config.last_login_name = user_name
    password_text = FE.input_type({By.XPATH: '//input[@placeholder="密码"]'}, driver)
    password_text.set_value(password)
    button = FE.button(text='登录')
    button.click()

def __logout(driver):
    '''
    登出
    :param driver:
    :return:
    '''
    try:
        nick_name = driver.find_element_by_attribute(
            'css selector', 'div.h-menu-submenu-title>span.nick-name', timeout=0.1)
        nick_name.move_to()
        out_li = driver.find_element_by_attribute(
            'xpath', './/span[text()="退出登录"]//ancestor::li[1]', timeout=0.1)
        out_li.secure_click()
        web_config.last_login_name = ''
        return True
    except Exception as e:
        logger.error(e)
        return False

def __close_driver(flag=True):
    '''
    全部浏览器驱动
    :param flag:
    :return:
    '''
    if flag:
        KC = KillChromedriver()
        KC.kill_chromedriver()
        logger.warning('关闭浏览器驱动！')
        return True
    else:
        logger.warning('未关闭浏览器驱动！')
        return False

def open_child_system(child_sys_name):
    '''
    打开顶层的子系统
    :param child_sys_name:
    :return:
    '''
    express = f'//div[contains(@class,"h-layout-head-sys-item") and contains(text(),"{child_sys_name}")]'
    visible = False
    index = 0
    while index < 3:
        res_check = display_wait(idname={By.XPATH: express}, flag=1,
                                 timeout=10, driver=FE.driver)
        logger.info(f'check child system element visible : {res_check}')
        if res_check:
            break
        # 刷新浏览器
        FE.driver.refresh()
        logger.info(f'check child system, refresh brower.')
        time.sleep(0.5)
        index += 1
    if visible:
        raise SeleniumError(f'连续{index}次等待元素 {express} 出现超时，请检查。')
    # 打开子系统
    list_ele = FE.list({By.CSS_SELECTOR: 'div.h-layout-head-sys'})
    list_ele.foud_target({By.CSS_SELECTOR: 'div.h-layout-head-sys-item'})
    list_ele.click_target(child_sys_name)
    logger.info(f'打开子系统 {child_sys_name}')
    return True


def open_menu_of_search(menu_name):
    '''
    通过搜索框打开菜单
    :param menu_name:
    :return:
    '''
    input_ele = FE.input_type({By.XPATH: './/input[@class="search"]'}, model='Nonstandard')
    input_ele.click()
    for _ in range(20):
        input_ele.set_value(Keys.BACK_SPACE)
    input_ele.set_value(menu_name)
    list_ele = FE.list({By.CSS_SELECTOR: 'div.menu'})
    list_ele.foud_target({By.CSS_SELECTOR: 'div.item', 'text': menu_name})
    list_ele.click()
    # 确认菜单已经打开
    timeout = 0
    while timeout < 5:
        HT = HomeTab(menu_name, FE.driver)
        if HT.element:
            logger.info(f'打开菜单 {menu_name}')
            break
        else:
            timeout += 0.1
    else:
        raise SeleniumError('未打开 {} 菜单页！'.format(menu_name))
